package Internal

import (
	"context"
	"github.com/bndr/gojenkins"
	"log"
)

// JenkinsToRun 是一个用于执行Jenkins任务的函数，接受一个文件名作为参数
func JenkinsToRun(FileName, DirName string) string {
	ctx := context.Background()
	// 1、创建与Jenkins服务器的连接
	//jenkins := gojenkins.CreateJenkins(nil, "http://192.168.0.3:8080/", "jenkins", "jenkins")
	jenkins := gojenkins.CreateJenkins(nil, "http://192.168.0.40:8080/", "kylin", "qwer1234")
	_, err := jenkins.Init(ctx)
	IsErr("jenkins.Init err:", err)
	// 连接成功
	log.Println("jenkinsServer is connecting !!!")

	//JobName := "test"
	JobName := "ehminer"
	// 2、获取指定Job的对象
	job, err := jenkins.GetJob(ctx, JobName)
	IsErr("jenkins.GetJob err:", err)
	log.Println(job.GetName())

	// 设置参数值
	params := map[string]string{"FileName": FileName, "DirName": DirName}

	// 构建Job，并传递参数
	JobBuildID, err := jenkins.BuildJob(ctx, JobName, params)
	IsErr("jenkins.BuildJob err:", err)

	for {
		// 根据构建ID获取构建信息
		build, err := jenkins.GetBuildFromQueueID(ctx, JobBuildID)
		IsErr("jenkins.GetBuildFromQueueID err :", err)

		if !build.IsRunning(ctx) {
			// 构建已完成，获取结果
			lastBuild, err := job.GetLastBuild(ctx)
			IsErr("job.GetLastBuild err:", err)
			// 获取最后一次构建的Console Output
			buildOutput := lastBuild.GetConsoleOutput(ctx)
			log.Println(buildOutput)

			result := build.GetResult()
			log.Println("Build Result:", result)
			return buildOutput
		}
	}
}

func IsErr(s string, err error) { //判断是否有error
	if err != nil {
		log.Println(s, err)
		return
	}
}
